﻿using System;
using System.Diagnostics;
using Windows.Phone.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using FunstreamTV.Common;
using FunstreamTV.Model;
using FunstreamTV.Tools;
using FunstreamTV.ViewModel;

namespace FunstreamTV
{
    public sealed partial class MainPage : Page
    {
        private NavigationHelper navigationHelper;
        public MainViewModel MainViewModel { get; set; }

        public MainPage()
        {
            this.InitializeComponent();
            HardwareButtons.BackPressed += HardwareButtons_BackPressed;
            this.navigationHelper = new NavigationHelper(this);
        }

        private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
        {
            Application.Current.Exit();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            DataContext = new MainViewModel();
            MainViewModel = (MainViewModel) DataContext;
            var success = await MainViewModel.Load();
            if (success)
                Frame.Navigate(typeof (ClientPage));

        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
            HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
        }

        private async void AuthClick(object sender, RoutedEventArgs e)
        {
            var response = await MainViewModel.Authorize();
            if (response.Item)
                Frame.Navigate(typeof (ClientPage));
        }
    }
}
